package Hxw3DEngine.core.controller
{
	import Hxw3DEngine.core.display.GameObject;
	import Hxw3DEngine.core.controller.RenderTree;
	import Hxw3DEngine.proxy.Stage3DProxy;
	
	import Hxw3DEngine.core.controller.Camera3D;
	import Hxw3DEngine.utils.FPS;
	
	import flash.events.EventDispatcher;
 
	//场景管理   到时候要写渲染管理
	public class Scene3D extends GameObject
	{
		public var camera:Camera3D;
		
		//当前场景所有的渲染树
		public var renderTreeList:Vector.<RenderTree>;
		
		public function Scene3D():void{
			renderTreeList = new Vector.<RenderTree>();
		}
		
		/**
		 *添加一个渲染对象到渲染列表 
		 * @param renderable 			渲染对象
		 * @param treeDepth				树深度
		 * @param depth					自身深度
		 */		
		override public function addChild(gameObject:GameObject,treeDepth:int = 0,depth:int = -1):void{
			var tree:RenderTree = getRenderTree(treeDepth);
			gameObject.renderTree = tree;
			gameObject.depth = tree.add(gameObject,depth);
		}
		
		/**
		 *根据深度取到对应的渲染树 
		 * @param depth		
		 */		
		private function getRenderTree(depth:int = 0):RenderTree{
			try
			{
				return renderTreeList[depth]
			} 
			catch(error:Error) 
			{
				return renderTreeList[depth] = new RenderTree(depth);
			}
			return null;
		}
		
		
		//渲染开始
		public function render():void{
			//清理图像
			Stage3DProxy.clear();
			//渲染个数初始化
			Stage3DProxy.renderGameobjectCount = 0;
			//总面数初始化
			Stage3DProxy.renderTriangles = 0;
			//drawCalls初始化
			Stage3DProxy.drawCalls = 0;
			//view
			Stage3DProxy.view.copyFrom(camera.viewMatrix);
			//project
			Stage3DProxy.proj.copyFrom(camera.perspectiveMatrix);
			//viewproject
			Stage3DProxy.viewProjection.copyFrom(camera.worldToClipMatrix);
			//camerapos
			Stage3DProxy.cameraPos.copyFrom(Stage3DProxy.camera.postion);
			
			draw();
			FPS.showRenderInfo(Stage3DProxy.renderGameobjectCount,Stage3DProxy.renderTriangles,Stage3DProxy.drawCalls);
			Stage3DProxy.present();
		}
		
		//画所有gameobject
		override public function draw():void{
			for each(var tree:RenderTree in renderTreeList){
				for each(var gameObject:GameObject in tree.renderList) {
					gameObject.draw();
					Stage3DProxy.clearBuffer();					
				}
			}
		}
		
	}
}